package com.example.nfc.server.utils.task;

import android.os.AsyncTask;

import com.example.nfc.server.utils.NLog;

import org.apache.http.HttpException;

/**
 * Create by 游德禄 on 2019-10-30
 */
public class Runable extends AsyncTask<Object, Integer, Object> {
    private Task.Action action;
    private Task.Listener listener;
    private OnFinish onFinish;
    private int position;
    protected int stepId = -1 ;
    private Object[] obj;
    public Runable(Task.Action action, Object...obj){
        this.action = action;
        this.obj = obj;
    }

    /**
     * 开始运行
     */
    public void start(int position,Task.Listener listener,OnFinish onFinish){
        this.position = position;
        if(listener!=null) {
            this.listener = listener;
        }
        this.onFinish = onFinish;
        super.execute(obj);
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(listener!=null){
            if(stepId!=-1){
                listener.started(stepId);
            }else{
                listener.started(position);
            }
        }
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        onFinish(o);
    }
    @Override
    protected Object doInBackground(Object... obj){
        try {
            return action.run(obj);
        }catch (Exception e){
            RunableNetErr err = new RunableNetErr();
            if (e instanceof HttpException) {
                err.setCode(1);
                err.setMsg("服务器故障,请稍后重试!");
            }else{
                err.setMsg("请求失败，请重试！");
                err.setCode(0);
            }
            return err;
        }
    }

    public void onFinish(Object o){
        if(listener!=null){
            boolean isOk = true;
            if(o instanceof RunableNetErr){
                isOk = false ;
            }
            try {
                if(stepId!=-1){
                    listener.finish(stepId,isOk,o);
                }else{
                    listener.finish(position,isOk,o);
                }
            }catch (Exception e){
                NLog.e("listener.finish",e.getMessage());
            }

        }
        if(onFinish!=null){
            onFinish.onfinish();
        }
    }
    public class RunableNetErr{
        private int code ;
        private String msg ;
        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }
    }
}
